<template>
  <a-form v-bind="$attrs" class="form" :rules="rules" ref="formRef" :model="formData" @finish="onSubmit">
    <a-form-item name="phoneNumber">
      <a-input
        v-bind="$attrs"
        placeholder="请输入手机号码"
        :maxlength="11"
        class="has-height"
        v-model:value.trim="formData.phoneNumber"
      ></a-input>
    </a-form-item>
    <a-form-item name="imageCode">
      <a-input v-bind="$attrs" v-model:value.trim="formData.imageCode" placeholder="请输入验证码" :maxlength="4">
        <template #suffix>
          <div class="img-box link" @click="getImageCode(true)">
            <img :src="imageUrl" alt="" />
          </div>
        </template>
      </a-input>
    </a-form-item>

    <a-form-item name="phoneCode">
      <a-input v-bind="$attrs" placeholder="请输入手机验证码" v-model:value.trim="formData.phoneCode" :maxlength="4">
        <template #suffix>
          <a-button
            type="link"
            class="p-0! h-22px!"
            tabindex="-1"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
            v-text="!state.smsSendBtn ? '获取验证码' : state.time + ' s'"
          >
          </a-button>
        </template>
      </a-input>
    </a-form-item>
    <div class="btn-box">
      <a-button v-bind="$attrs" type="primary" :loading="loading" html-type="submit">注册/登录</a-button>
    </div>
  </a-form>
</template>

<script lang="ts">
export default {
  inheritAttrs: true,
};
</script>

<script lang="ts" setup>
import UserService from '@/api/user';
import { useUserStore } from '@/store/user';
import { message } from 'ant-design-vue';
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
// import { rules } from '../util';

const rules = {};

// const agreePrefix = '';
const formRef = ref();
const imageUrl = ref();
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const checked = ref(false);
const formData = reactive({
  phoneNumber: null,
  imageCode: null,
  imageId: null,
  phoneCode: null,
});
const state = reactive({ smsSendBtn: false, time: 60 });
const loading = ref(false);
const interval = ref();
async function onSubmit() {
  if (!checked.value && route.name === 'Login') {
    message.warn(`请先阅读并同意协议`);
    return;
  }
  loading.value = true;
  try {
    await formRef.value?.validate();
    const params = {
      phoneNumber: formData.phoneNumber,
      phoneCode: formData.phoneCode,
    };
    const resp = await UserService.login(params);
    if (resp.code === 200) {
      message.success(resp?.msg || '登录成功');
      const data = resp.data;
      userStore.setUserId(data?.id);
      userStore.setImToken(data?.imToken);
      userStore.setToken(data?.tokenValue);
      userStore.setTokenHeader(data?.tokenName);
      window.location.reload()
    } else {
      message.error(resp?.msg || '登录失败');
      getImageCode(true);
      loading.value = false;
    }
  } catch (error) {
    console.log(error);
    loading.value = false;
  }
}

async function getImageCode(flag = false) {
  if (flag) {
    formData.phoneCode = null;
  }
  const resp = await UserService.getImageCode();

  if (resp.code === 200) {
    imageUrl.value = resp.data?.imageBase64;
    formData.imageId = resp.data?.id;
  }
}

async function getCaptcha() {
  try {
    await formRef.value.validateFields(['phoneNumber', 'imageCode']);
    state.smsSendBtn = true;
    interval.value = window.setInterval(() => {
      if (state.time-- <= 0) {
        state.time = 60;
        state.smsSendBtn = false;
        window.clearInterval(interval.value);
      }
    }, 1000);

    const resp = await UserService.getMobileCode({ ...formData });
    if (resp.code === 200) {
      message.success(resp.msg || '', 1);
    } else {
      message.error(resp.msg || '', 1);
      state.time = 60;
      state.smsSendBtn = false;
      window.clearInterval(interval.value);
    }
  } catch (error) {
    console.log(error);
  }
}

getImageCode();
</script>

<style lang="scss" scoped>
.form {
  &.ant-form {
    .ant-btn-link {
      padding-left: 0;
      padding-right: 0;
    }
    .img-box {
      height: 30px;
      border-radius: 4px;
      overflow: hidden;
      @apply my--7px;
      img {
        height: 100%;
      }
    }
    .ant-input,
    .ant-input-affix-wrapper {
      border-radius: 4px;
    }

    .btn-box {
      margin-top: 20px;
      .ant-btn {
        width: 100%;
      }
    }
  }
}
</style>
